package com.banshuibao.bsb_android.util;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by wangpan on 2017/4/5.
 * String 转 map
 * map 转 String
 */

public class JsonConversionMap {

    public static HashMap parserToMap(String s) throws JSONException {
        HashMap map = new HashMap();
        JSONObject json = new JSONObject(s);
        Iterator keys = json.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String value = json.get(key).toString();
            if (value.startsWith("{") && value.endsWith("}")) {
                map.put(key, parserToMap(value));
            } else {
                map.put(key, value);
            }

        }
        return map;
    }

    /**
     * 将hashMap转为json
     */
    public static String hashMapToJson(HashMap map) {
        String string = "{";
        for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry e = (Map.Entry) it.next();
            string += "'" + e.getKey() + "':";
            string += "'" + e.getValue() + "',";
        }
        string = string.substring(0, string.lastIndexOf(","));
        string += "}";
        return string;
    }

    /**
     * 将字符串以“，”分割转为集合
     * */
    public static List<String> toList(String json){
        List<String> list=new ArrayList<>();
        if(!TextUtils.isEmpty(json)) {
            String[] split = json.split(",");
            for (int i = 0; i < split.length; i++) {
                if (!TextUtils.isEmpty(split[i])) {
                    list.add(split[i]);
                }
            }
        }
        return list;
    }

}
